package fightplan.actions;

import java.awt.event.ActionEvent;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.JFileChooser;

import fightplan.business.Sheet;
import fightplan.persistence.FilePersistence;
import fightplan.views.ClientView;

@SuppressWarnings("serial")
public class SaveSheetAction extends AbstractAction {

	private ClientView clientView;

	private boolean saveAs;

	public SaveSheetAction(ClientView clientView, boolean saveAs) {
		super(saveAs ? "Blatt speichern als..." : "Blatt speichern");
		this.clientView = clientView;
		this.saveAs = saveAs;
	}

	public void actionPerformed(ActionEvent actionEvent) {
		Sheet sheet = (Sheet) clientView.getSheet().getValue();
		if (sheet == null)
			return;
		File file = sheet.file;

		if (saveAs) {
			JFileChooser fileChooser = new JFileChooser();
			fileChooser.setSelectedFile(file);
			fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
			fileChooser.setDialogTitle("Blatt Speichern");
			fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
				public boolean accept(File f) {
					return !f.isFile() || f.getName().endsWith(".page");
				}

				public String getDescription() {
					return "TRN (Turnier) (*.page)";
				}
			});
			if (fileChooser.showDialog(clientView, "Speichern") == JFileChooser.APPROVE_OPTION) {
				file = fileChooser.getSelectedFile();
			} else {
				return;
			}
		}
		FilePersistence.save(file, (Sheet) clientView.getSheet().getValue());
	}

}